﻿using System.Collections.Generic;
using System.Linq;
using Missbot.Common;
using Missbot.Service;
using Dolany.UtilityTool;
using Missbot.Core.CrossingRoute;

namespace Missbot.AIModule.Gaming.SegmentAttach
{
    public class SegmentSvc : IDataMgr, ISingleton, IViewable
    {
        public List<TouhouTreasure> Treasures;

        public SegmentModel RandSegment()
        {
            var randTreasure = Treasures.RandElement();
            return randTreasure.Segments.RandElement();
        }

        public TouhouTreasure FindTreasureBySegment(string segmentName)
        {
            return Treasures.FirstOrDefault(p => p.Segments.Any(s => s.Name == segmentName));
        }

        public TouhouTreasure FindTreasureByName(string treasureName)
        {
            return Treasures.FirstOrDefault(p => p.Name == treasureName);
        }

        public SegmentModel FindSegmentByName(string segmentName)
        {
            return Treasures.SelectMany(p => p.Segments).FirstOrDefault(p => p.Name == segmentName);
        }

        public void RefreshData()
        {
            Treasures = TouhouTreasureDA.GetAll();
        }

        public (bool canView, string viewCommand) ViewableCheck(string name)
        {
            if (FindTreasureByName(name) != null)
            {
                return (true, "查看宝藏");
            }
            
            return FindSegmentByName(name) == null ? (false, null) : (true, "查看宝藏碎片");
        }
    }
    
    public class TouhouTreasure : DbBaseEntity
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public string FileID { get; set; }

        public List<SegmentModel> Segments { get; set; }
    }

    public static class TouhouTreasureDA
    {
        public static List<TouhouTreasure> GetAll()
        {
            return MongoService<TouhouTreasure>.Get();
        }
        
        public static string Format(this TouhouTreasure entity)
        {
            return $"【{entity.Name}】\n{entity.Description}\n需要碎片：{string.Join("⭐", entity.Segments.Select(s => $"【{s.Name}】"))}";
        }
        
        public static bool IsMatch(this TouhouTreasure entity, string segment1, string segment2)
        {
            return entity.Segments.Any(s => s.Name == segment1) && entity.Segments.Any(s => s.Name == segment2) && segment1 != segment2;
        }
    }

    public class SegmentModel
    {
        public string Name { get; set; }

        public string Description { get; set; }

        public string FileID { get; set; }
        
        public override string ToString()
        {
            return $"【{Name}】\n{Description}";
        }
    }
}